#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<cstring>
#include<string>
#define Size 512

void SubProcessWrite(int wfd);
void FarProcessRead(int rfd);
std::string GetOtherMessage();

int main()
{
    //1.创建管道
    int pipefd[2];
    int n = pipe(pipefd);
    //pipefd[0]——>r pipefd[1]——>w
    if(n != 0)
    {
        std::cerr<<"errno："<<errno;
        return 1;
    }

    //2.创建子进程
    int lid = fork();
    if(lid == 0)
    {
        close(pipefd[0]);//关闭读文件
        SubProcessWrite(pipefd[1]);
        close(pipefd[1]);
        exit(0);
    }
    close(pipefd[1]);//关闭写文件
    close(pipefd[0]);
    //FarProcessRead(pipefd[0]);


    //观察子进程被13号信号杀死
    int status = 0;
    pid_t rid = waitpid(0,&status,0);
    if(rid > 0)
    {
        std::cerr<<"exit code:"<<(status&0x7F)<<std::endl;
        std::cerr<<"exit signal:"<<(status>>8&0xFF)<<std::endl;
    }
    
    return 0;
}



std::string GetOtherMessage()
{
    static int cnt = 0;
    std::string messageid = std::to_string(cnt++);//输出变化信息
    std::string message = "massageid:";
    message += messageid;
    message += "my pid is:" + std::to_string(getpid());
    return message;

}
void SubProcessWrite(int wfd){
    std::cerr<<"读文件关闭，子进程准备通信------------"<<std::endl;
    std::string message = "Dad,I`m your son.";
    while(1)
    {
        sleep(1);
        message = message + GetOtherMessage();
        write(wfd,message.c_str(),message.size());//不会写入'/0'
    }
}
void FarProcessRead(int rfd){
    std::cout<<"写文件关闭，父进程准备通信------------"<<std::endl;
    char inbuffer[Size];
    
    while(1)
    {
        sleep(2);
        ssize_t n = read(rfd,inbuffer,Size-1);//预留空间
        inbuffer[n] = '\0';
        std::cout<<"farther get message:   "<<inbuffer<<std::endl;
    }
    
}
